<style scoped>
#photo .mask {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

#photo {
  height: 9.5rem;
  /* height: calc(100% - 28px); */
  position: relative;
}
</style>

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="成员名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="成员性别" prop="sex" style="width: 200px">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="加入日期" prop="joinDate">
        <el-date-picker
          clearable
          v-model="queryParams.joinDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择加入日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:branchMember:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:branchMember:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:branchMember:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:branchMember:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="branchMemberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="照片" align="center" prop="image">
        <template #default="scope">
          <img :src="scope.row.image" alt="人像" width="55" />
        </template>
      </el-table-column> -->
      <el-table-column label="名称" align="center" prop="name">
        <template #default="scope">
          <el-tooltip effect="light" placement="left">
            <template #content>
              <img v-if="scope.row.image" :src="scope.row.image" alt="人像" width="60" />
              <span v-else>暂无照片</span>
            </template>
            <span>{{ scope.row.name }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center">
        <template #default="scope">
          <span>{{ calculateAge(parseTime(scope.row.birthday, "{y}-{m}-{d}")) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出生地" align="center" prop="nativePlace" />
      <el-table-column label="出生日期" align="center" prop="birthday">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加入日期" align="center" prop="joinDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.joinDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="个人简介" align="center" prop="introduction">
        <template #default="scope">
          <el-link @click="proxy.$modal.alert(scope.row.introduction, '个人简介')" type="primary" :underline="false" >查看简介</el-link >
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="proxy.$modal.alert(scope.row.introduction, '个人简介')"
            >简介</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:branchMember:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:branchMember:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改支部成员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="branchMemberRef" :model="form" :rules="rules" label-width="80px">
        <!-- TODO 这里记得改成uid，后端也得改 -->
        <el-form-item label="绑定用户" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择已存在的用户">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="parseInt(user.userId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称性别" required>
          <el-col :span="11">
            <el-form-item prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center">
            <span style="color: darkgray">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="两个日期" required>
          <el-col :span="11">
            <el-tooltip effect="dark" content="出生日期" placement="left">
              <el-form-item prop="birthday">
                <el-date-picker
                  clearable
                  v-model="form.birthday"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择出生日期" />
              </el-form-item>
            </el-tooltip>
          </el-col>
          <el-col :span="2" style="text-align: center">
            <span style="color: darkgray">|</span>
          </el-col>
          <el-col :span="11">
            <el-tooltip effect="dark" content="加入日期" placement="right">
              <el-form-item prop="joinDate">
                <el-date-picker
                  clearable
                  v-model="form.joinDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择加入日期" />
              </el-form-item>
            </el-tooltip>
          </el-col>
        </el-form-item>
        <el-form-item label="出生地" prop="nativePlace">
          <el-cascader
            placeholder="请选择出生地"
            v-model="area"
            :options="pcaTextArr"
            @change="form.nativePlace = area.join(' ')" />
        </el-form-item>
        <el-form-item label="照片" prop="image">
          <!-- <image-upload v-model="form.image" :limit="1" /> -->
          <div id="photo" @mouseover="show = true" @mouseleave="show = false">
            <img v-if="form.image" :src="form.image" width="100%" height="100%" alt="证件照" />
            <el-skeleton-item
              v-else
              variant="image"
              style="width: 108px; height: 100%; background: var(--el-fill-color-light)" />
            <Transition name="el-fade-in-linear">
              <div class="mask" v-show="show" @click="fileInput?.click">
                <input type="file" accept="image/*" style="display: none" ref="fileInput" @change="convertToBase64" />
                <el-icon color="white"><Edit /></el-icon>
              </div>
            </Transition>
          </div>
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            :autosize="{ minRows: 1, maxRows: 5 }"
            v-model="form.introduction" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BranchMember">
import {
  listBranchMember,
  getBranchMember,
  delBranchMember,
  addBranchMember,
  updateBranchMember,
} from "@/api/system/branchMember";
import { listUser } from "@/api/system/user";
import { pcaTextArr } from "element-china-area-data";

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");

const branchMemberList = ref([]);
const userList = ref([]);
const open = ref(false);
const show = ref(false);
const fileInput = ref();
const loading = ref(true);
const showSearch = ref(true);
const area = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    sex: null,
    joinDate: null,
  },
  rules: {
    // uid: [{ required: true, message: "UID不能为空", trigger: "blur" }],
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
    nativePlace: [{ required: true, message: "出生地不能为空", trigger: "change" }],
    birthday: [{ required: true, message: "出生日期不能为空", trigger: "blur" }],
    joinDate: [{ required: true, message: "加入日期不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询支部成员列表 */
function getList() {
  loading.value = true;
  listBranchMember(queryParams.value).then((response) => {
    branchMemberList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询用户列表 */
function getUserList() {
  listUser({ pageSize: 100 }).then((response) => {
    userList.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    sex: null,
    nativePlace: null,
    birthday: null,
    joinDate: null,
    image: null,
    introduction: null,
  };
  proxy.resetForm("branchMemberRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getUserList();
  open.value = true;
  title.value = "添加支部成员";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getUserList();
  const _id = row.id || ids.value;
  getBranchMember(_id).then((response) => {
    form.value = response.data;
    console.log(form.value);
    area.value = form.value.nativePlace?.split(" ");
    open.value = true;
    title.value = "修改支部成员";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["branchMemberRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBranchMember(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBranchMember(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除支部成员编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delBranchMember(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/branchMember/export",
    {
      ...queryParams.value,
    },
    `branchMember_${new Date().getTime()}.xlsx`
  );
}

/** 计算年龄 */
function calculateAge(birthDate) {
  var today = new Date();
  var birth = new Date(birthDate);
  var age = today.getFullYear() - birth.getFullYear();
  var monthDiff = today.getMonth() - birth.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
}

/** 图片转base64 */
const convertToBase64 = (event) => {
  const target = event.target;
  if (target.files && target.files[0]) {
    const file = target.files[0];
    if (file.size > 2097152) {
      proxy.$modal.msgWarning("请上传大小不超过2MB的图片");
      return;
    }
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      form.value.image = reader.result;
    };
  }
};

getList();
</script>
